package com.cdu.controller;

import com.cdu.util.FastDFSUtils;
import com.cdu.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author: Nemo Chen(姓名) 764291197@qq.com(邮箱) cfh10260108(微信)
 * @date: 2020/1/8 9:26
 * @Description:
 */

@CrossOrigin
@Api("分布式文件系统管理")
@RestController
@RequestMapping("/fdfs")
public class FastDFSController {

    @PostMapping("upload")
    @ApiOperation(value = "实现文件上传", notes = "实现文件上传")
    @ApiImplicitParams({
    })
    public Result fileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            return Result.ok().putData(FastDFSUtils.upload(file));
        }
        return Result.error();
    }

    @GetMapping("delete")
    @ApiOperation(value = "删除文件", notes = "删除文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileKey", value = "文件主键地址", paramType = "query", dataType = "String", required = true),
    })
    public Result fileDelete(@RequestParam String fileKey) {
        try {
            FastDFSUtils.deleteFile("group1", fileKey);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error();
    }

    @GetMapping("down")
    @ApiOperation(value = "下载文件", notes = "获得文件的流")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileKey", value = "文件主键地址", paramType = "query", dataType = "String", required = true),
    })
    public void downFile(@RequestParam String fileKey, HttpServletResponse response) throws UnsupportedEncodingException {
        InputStream is = FastDFSUtils.downFile("group1", fileKey);
        String downName = fileKey.substring(fileKey.lastIndexOf("/") + 1);
        if (is != null) {
            response.setContentType("application/x-execl");
            response.setCharacterEncoding("UTF-8");
//                response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(one.getFileName(),"UTF-8"));
            String headStr = "attachment; filename=\"" + java.net.URLEncoder.encode(downName, "UTF-8") + "\"";
            response.setHeader("Content-Disposition", headStr);
//                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            byte[] buffer = new byte[1024];
            try (OutputStream os = response.getOutputStream();) {
                int i = is.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = is.read(buffer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
